package com.wuwei.utils;

import com.wuwei.pojo.Product;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.IOException;
import java.lang.reflect.Array;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

/**
 * @description: JDParseUtils <br>
 * @date: 2021/2/28 11:11 <br>
 * @author: wuwei666 <br>
 * @version: 1.0 <br>
 */
public class JDParseUtils {
    public static List<Object> getmsg(String keyword) throws Exception {
        String url = "https://search.jd.com/Search?keyword=" + keyword;
        ArrayList<Object> list = new ArrayList<>();
        Document document = Jsoup.parse(new URL(url), 30000);
        Element element = document.getElementById("J_goodsList");
        Elements li = element.getElementsByTag("li");
        for (Element e : li) {
            String price = e.getElementsByClass("p-price").eq(0).text();
            String name = e.getElementsByClass("p-name").eq(0).text();
            String imgUrl = e.getElementsByTag("img").eq(0).attr("data-lazy-img");
            Product product = new Product(name,price,imgUrl);
            list.add(product);
        }
        return list;
    }






    public static void main(String[] args) throws IOException {
        String url = "https://search.jd.com/Search?keyword=java";
        // 解析网页
        Document document = Jsoup.parse(new URL(url), 30000);
        Element element = document.getElementById("J_goodsList");
        Elements li = element.getElementsByTag("li");
        for (Element e : li) {
            String price = e.getElementsByClass("p-price").eq(0).text();
            String name = e.getElementsByClass("p-name").eq(0).text();
            String imgUrl = e.getElementsByTag("img").eq(0).attr("data-lazy-img");
            System.out.println(name);
            System.out.println(price);
            System.out.println(imgUrl);
            System.out.println("================");
        }
    }
}
